package com.dianrui.fmi.community;

import android.Manifest;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.os.Build;
import android.support.annotation.NonNull;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;

import com.dianrui.fmi.Constant;
import com.dianrui.fmi.MyApplication;
import com.dianrui.fmi.R;
import com.dianrui.fmi.activity.BaseActivity;
import com.dianrui.fmi.activity.BigImageActivity;
import com.dianrui.fmi.event.RfreshAnswer;
import com.dianrui.fmi.event.RfreshCommunity;
import com.dianrui.fmi.event.RfreshFavorites;
import com.dianrui.fmi.event.RfreshQuestion;
import com.dianrui.fmi.util.BitmapUtils;
import com.dianrui.fmi.util.ConvertUtils;
import com.dianrui.fmi.util.GlideUtil;
import com.dianrui.fmi.util.MyUtil;
import com.dianrui.fmi.util.OkHttpUtils;
import com.dianrui.fmi.util.StringUtils;
import com.dianrui.fmi.util.ToastUtil;
import com.dianrui.fmi.util.Url;
import com.dianrui.fmi.view.ninegride.NineView;
import com.dianrui.fmi.view.ninegride.RatioImageView;

import org.greenrobot.eventbus.EventBus;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;
import cn.finalteam.galleryfinal.GalleryFinal;
import cn.finalteam.galleryfinal.model.PhotoInfo;


public class PublishCommuityActivity extends BaseActivity implements NineView.NineViewShowCallBack{
    private List<String> imageList = new ArrayList<>();
    private ProgressDialog pd;


    @BindView(R.id.title)
    TextView title;
    @BindView(R.id.input_community)
    EditText inputCommunity;
    @BindView(R.id.nine)
    NineView nine;



    @Override
    public int getContentViewId() {
        return R.layout.activity_publish_community;
    }

    @Override
    public void initView() {
        pd = new ProgressDialog(PublishCommuityActivity.this);
        title.setText(getString(R.string.publish));
        checkLocationPerssions();
        imageList.add("default");
        nine.maxCount(9).CloseSize(70).isShowCloseButton(true).spacing(3).setNineViewShowCallBack(this).setUrlList(imageList);

    }


    //检查是否开启定位权限,有其故意关闭权限进入APP后也要有权限提醒设置
    private void checkLocationPerssions() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            if (ContextCompat.checkSelfPermission(this, Manifest.permission.CAMERA) == PackageManager.PERMISSION_GRANTED) {
                nine.maxCount(9).CloseSize(70).isShowCloseButton(true).spacing(3).setNineViewShowCallBack(this).setUrlList(imageList);
            } else {
                ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.CAMERA}, 1);
            }
        }else {
            nine.maxCount(9).CloseSize(70).isShowCloseButton(true).spacing(3).setNineViewShowCallBack(this).setUrlList(imageList);
        }

    }


    @OnClick({R.id.back, R.id.publish})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.back:
                finish();
                break;
            case R.id.publish:
                if (StringUtils.isEmpty(inputCommunity.getText().toString())) {
                    ToastUtil.showToast(getString(R.string.please_input_community_empty));
                    return;
                }
                Publish();
                break;

                default:
                    break;
        }
    }

    private void Publish() {
        pd.setMessage(getString(R.string.submiting));
        pd.show();
        pd.setCancelable(false);
        pd.setCanceledOnTouchOutside(false);
        JSONArray jsonArray = new JSONArray();
        for (int i = 0; i < imageList.size(); i++) {
            if (!"default".equals(imageList.get(i))) {
                jsonArray.put(ConvertUtils.bitmapToBase64(BitmapUtils.decodeSampledBitmapFromFile(imageList.get(i), 480, 960)));
            }
            try {
                JSONObject jsonObject = new JSONObject();
                jsonObject.put("picture", jsonArray);
                jsonObject.put("contents", inputCommunity.getText().toString().trim());
                jsonObject.put("is_drafts", "1");
                OkHttpUtils.getInstance().postWithMemberToken(Url.PUBLISHCOMMUNITY, jsonObject.toString(), new OkHttpUtils.XCallBack() {

                    @Override
                    public void onResponse(String response) {
                        if (!StringUtils.isEmpty(response)) {
                            try {
                                final JSONObject jsonObject = new JSONObject(response);
                                if (null != jsonObject &&!isFinishing()) {
                                    if (Constant.DATASUCCESS.equals(jsonObject.optString("status"))) {
                                        pd.dismiss();
                                        EventBus.getDefault().post(new RfreshFavorites());
                                        EventBus.getDefault().post(new RfreshCommunity());
                                        EventBus.getDefault().post(new RfreshQuestion());
                                        EventBus.getDefault().post(new RfreshAnswer());
                                        ToastUtil.showToast(jsonObject.optString("message"));
                                        finish();
                                    } else {
                                        pd.dismiss();
                                        ToastUtil.showToast(jsonObject.optString("message"));
                                    }

                                }
                            } catch (JSONException e) {
                                e.printStackTrace();
                            }
                        }else {
                            pd.dismiss();
                            ToastUtil.showToast(getString(R.string.net_error));
                        }
                    }
                });
            } catch (JSONException e) {
                e.printStackTrace();
            }

        }

    }

    @Override
    public void onDisplayOneImage(RatioImageView imageView, String url, int parentWidth, Context context) {
        if ("default".equals(url)) {
            addImageViewList(GlideUtil.glideLoad(false, imageView, PublishCommuityActivity.this, R.mipmap.add_photo));
        } else {
            imageView.setTag(R.id.glide_tag, url);
            addImageViewList(GlideUtil.downLoader(false, imageView, PublishCommuityActivity.this));
        }
    }

    @Override
    public void onDisplayImage(RatioImageView imageView, RatioImageView closeButton, String url, int parentWidth, Context context) {
        if ("default".equals(url)) {
            addImageViewList(GlideUtil.glideLoad(false, imageView, PublishCommuityActivity.this, R.mipmap.add_photo));
            if (closeButton != null) {
                closeButton.setVisibility(View.GONE);
            }
        } else {
            imageView.setTag(R.id.glide_tag, url);
            addImageViewList(GlideUtil.downLoader(false, imageView, PublishCommuityActivity.this));
            if (closeButton != null) {
                closeButton.setVisibility(View.VISIBLE);
            }
        }
    }

    @Override
    public void onClickImage(int position, String url, List<String> urlList, Context context) {
        if ("default".equals(url)) {
            int count = 9;
            if (imageList.size() > 1) {
                count = 9 - imageList.size() + 1;
            }
            MyUtil.createPhotoChooseDialog(0, count, PublishCommuityActivity.this, MyApplication.getFunctionConfig(), new GalleryFinal.OnHanlderResultCallback() {
                @Override
                public void onHanlderSuccess(int reqeustCode, List<PhotoInfo> resultList) {
                    if (resultList == null || resultList.size() == 0) {
                        return;
                    }

                    for (int i = 0; i < imageList.size(); i++) {
                        if ("default".equals(imageList.get(i))) {
                            imageList.remove(i);
                        }
                    }
                    for (int i = 0; i < resultList.size(); i++) {
                        imageList.add(resultList.get(i).getPhotoPath());
                    }
                    if (imageList.size() < 9) {
                        imageList.add("default");
                    }
                    nine.urlList(imageList);

                }

                @Override
                public void onHanlderFailure(int requestCode, String errorMsg) {}
            });
        }else {
            List<String> temp = new ArrayList<>();
            int count = 0;
            for (int i = 0; i < imageList.size(); i++) {
                if (!"default".equals(imageList.get(i))) {
                    temp.add(imageList.get(i));
                } else {
                    count++;
                }
            }
            startActivity(new Intent(PublishCommuityActivity.this, BigImageActivity.class)
                    .putStringArrayListExtra("data", (ArrayList<String>) temp)
                    .putExtra("current", position));
        }
    }

    @Override
    public void onClickImageColse(int position, String url, List<String> urlList, Context context) {
        imageList.remove(position);
        int count = 0;
        for (int i = 0; i < imageList.size(); i++) {
            if ("default".equals(imageList.get(i))) {
                count++;
            }
        }
        if (count == 0) {
            imageList.add("default");
        }

        nine.urlList(imageList);
    }

    @Override
    public void onSamePhotos(List<String> mRejectUrlList) {

    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        switch (requestCode) {
            case 1:
                if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {

                }
                break;
            default:
                break;

        }
    }


    @Override
    protected void onDestroy() {
        if (pd != null && pd.isShowing()) {
            pd.dismiss();
        }
        if (imageList != null) {
            imageList.clear();
        }
        super.onDestroy();
    }
}
